package controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.PageReturn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import common.ImgUtil;
import pojo.*;
import service.CommentServiceI;
import service.EssayServiceI;
import service.MessageServiceI;
import service.UserServiceI;

/**
 * 
 * @ClassName: UserController
 * @Description:用户相关
 * @author: jiao
 * @date: 
 */

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserServiceI uServiceI;

	private static Integer LimitNumber = 20;
	/**
	 * 
	 * @Title: login   
	 * @Description: //登录
	 * @param: @param user
	 * @param: @param request
	 * @param: @param session
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("login")
	@ResponseBody
	public String login(User user, HttpServletRequest request, HttpSession session) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String vercode = request.getParameter("vercode");
		String check_vercode = (String) request.getSession().getAttribute("loginvercode");// 获取session的验证码
		if (!vercode.toLowerCase().equals(check_vercode.toLowerCase())) {
			return "wrongvercode";// 验证码错误
		}
		user = uServiceI.Login(username);//根据用户名登录
		if (user != null) {
			session.setAttribute("user", user);
			session.setMaxInactiveInterval(30 * 60);// 设置session生存时间
			if (password.equals(user.getPassword())) {// 比对密码
				return "success";
			} else {
				return "false";
			}
		} else
			return "false";

	}
	/**
	 * @Title: successlogin   
	 * @Description: 	//成功登录跳转
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("successlogin")
	public String successlogin() {
		return "redirect:/essay/essayread.do";
	}

	/**
	 * 
	 * @Title: logincode   
	 * @Description: 	//登录验证码
	 * @param: @param request
	 * @param: @param response
	 * @param: @throws IOException      
	 * @return: void      
	 * @throws
	 */
	@RequestMapping("logincode")
	public void logincode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		char[] array = ImgUtil.getStr();
		request.getSession().setAttribute("loginvercode", String.valueOf(array));
		BufferedImage image = ImgUtil.getImage(array);
		ImageIO.write(image, "JPG", response.getOutputStream());
	}

	/**
	 * 
	 * @Title: register   
	 * @Description: 	//注册
	 * @param: @param user
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("register")
	@ResponseBody
	public String register(User user, HttpServletRequest request) {
		String username = request.getParameter("username");
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");
		String vercode = request.getParameter("vercode");
		String check_vercode = (String) request.getSession().getAttribute("registervercode");// 获取session的验证码
		if (!vercode.toLowerCase().equals(check_vercode.toLowerCase())) {
			return "wrongvercode";
		}
		int grade = 1;
		int integration=0;
		user.setUserName(username);
		user.setPhone(phone);
		user.setPassword(password);
		user.setGrade(grade);
		user.setIntegration(integration);
		user.setIntroduce("这个用户很懒，还没有签名");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = df.format(new Date());
		user.setJoinDate(date);
		User user2 = new User();
		user2 = uServiceI.Login(username);// 查看是否用户名重复
		if (user2 != null) {
			return "exist";
		}
		int i = uServiceI.Register(user);
		if (i > 0) {
			return "success";
		} else
			return "false";
	}

	/**
	 * 
	 * @Title: registercode   
	 * @Description:	// 注册验证码
	 * @param: @param request
	 * @param: @param response
	 * @param: @throws IOException      
	 * @return: void      
	 * @throws
	 */
	@RequestMapping("registercode")
	public void registercode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		char[] array = ImgUtil.getStr();
		request.getSession().setAttribute("registervercode", String.valueOf(array));
		BufferedImage image = ImgUtil.getImage(array);
		ImageIO.write(image, "JPG", response.getOutputStream());
	}

	/**
	 * 
	 * @Title: logout   
	 * @Description: 	// 登出
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request) {
		if (request.getSession() != null) {
			request.getSession().invalidate();// 销毁session
		}
		return "redirect:/essay/essayread.do";
	}

	/**
	 * 
	 * @Title: userhome   
	 * @Description: 	// 用户主页
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@Autowired
	private EssayServiceI essayServiceI;
	@Autowired
	private CommentServiceI commentServiceI;
	@RequestMapping("userhome")
	public ModelAndView userhome(HttpServletRequest request,ModelAndView modelAndView) {
		User user=(User) request.getSession().getAttribute("user");
		if (user==null) {
			modelAndView.setViewName("redirect:/login.html");
		}else {
			Integer userId=user.getUserId();
			/*******************按照发表时间显示文章*********************/
			List<Essay> publishDateList=essayServiceI.ShowUserEssayByDateNoLimit(userId);
			/********************按照评论数量*********************/
			List<Integer> essayIdList=commentServiceI.FindEssayIdByUserId(userId);
			List<Essay> essaylist=new ArrayList<Essay>();
			for (Integer essayId : essayIdList) {
				Essay essay=essayServiceI.FindEssay(essayId);
				essaylist.add(essay);
			}
			modelAndView.addObject("publishDateList", publishDateList);
			modelAndView.addObject("essaylist",essaylist);
			modelAndView.setViewName("/community/jsp/user/userhome");
		}
		return modelAndView;
	}

	/**
	 * 
	 * @Title: userset   
	 * @Description: 	// 用户设置跳转
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("userset")
	public String userset(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		if(user!=null) {
			User user2 = uServiceI.FindUserById(user.getUserId());
			if (request.getSession() != null) {
				request.getSession().invalidate();// 销毁session
				request.getSession().setAttribute("user", user2);// 重新注入session
			}
		}
		return "/community/jsp/user/userset";
	}

	/**
	 * 
	 * @Title: updateuser   
	 * @Description: 	// 更新用户
	 * @param: @param user
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("updateuser")
	@ResponseBody
	public String updateuser(User user, HttpServletRequest request) {
		User user2 = (User) request.getSession().getAttribute("user");
		Integer userId = user2.getUserId();
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String realname = request.getParameter("realname");
		String identityNumber = request.getParameter("identityNumber");
		String birthday = request.getParameter("birthday");
		String address = request.getParameter("city");
		String username = request.getParameter("username");
		String sign = request.getParameter("sign");
		String sex = request.getParameter("sex");
		/*System.out.println(sex);*/
		Integer realsex = 0;
		if (sex.equals("1")) {
			realsex = 1;
		} else if (sex.equals("0")) {
			realsex = 0;
		}
		/*
		 * System.out.println(email+"---"+phone+"---"+realname+"---"+identityNumber+
		 * "---"+birthday+"---"+city+"---"+username+"---"+sign+"---"+sex);
		 */
		user.setUserId(userId);
		user.setUserName(username);
		user.setRealName(realname);
		user.setIdentityNumber(identityNumber);
		user.setPhone(phone);
		user.setEmail(email);
		user.setAddress(address);
		user.setBirthday(birthday);
		user.setIntroduce(sign);
		user.setSex(realsex);
		int i = uServiceI.CompleteUserInformation(user);
		if (i > 0) {
			User user3 = new User();
			user3 = uServiceI.FindUserById(userId);
			if (request.getSession() != null) {
				request.getSession().invalidate();// 销毁session
				request.getSession().setAttribute("user", user3);// 注入session
			}
			return "success";
		} else
			return "false";
	}

	/**
	 * 
	 * @Title: redirectIndex   
	 * @Description: 	//跳转首页
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("redirectIndex")
	public String redirectIndex(HttpServletRequest request) {
		return "redirect:/essay/essayread.do";
	}

	/**
	 * 
	 * @Title: resetPassword   
	 * @Description: 	// 重置密码
	 * @param: @param user
	 * @param: @param session
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("resetPassword")
	@ResponseBody
	public String resetPassword(User user, HttpSession session, HttpServletRequest request) {
		String password = request.getParameter("password");
		User user2 = (User) session.getAttribute("user");
		user.setUserId(user2.getUserId());
		user.setPassword(password);
		int i = uServiceI.ResetPassword(user);
		if (i > 0) {
			return "success";
		} else
			return "false";
	}

	/**
	 * 
	 * @Title: redirectuserindex   
	 * @Description: 	//跳转用户主页
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("userindex")
	public String redirectuserindex() {
		return "redirect:/essay/essayreadbyuser.do";
	}

	/**
	 * 
	 * @Title: usermessage   
	 * @Description: 	//用户我的消息页面的跳转
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@Autowired
	private MessageServiceI messageServiceI;
	@RequestMapping("usermessage")
	public ModelAndView usermessage(HttpSession session,ModelAndView modelAndView) {
		User user=(User) session.getAttribute("user");
		if(user==null) {
			modelAndView.setViewName("/community/jsp/user/unlogindex");
		}else {
			Integer userId=user.getUserId();
			List<Message> messages=messageServiceI.FindAllMessage(userId);
			modelAndView.addObject("messages",messages);
			modelAndView.setViewName("/community/jsp/user/usermessage");
		}
		return modelAndView;
	}

	/**
	 * 
	 * @Title: otheruserhome   
	 * @Description:	//其他人的用户中心
	 * @param: @param request
	 * @param: @param session
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@RequestMapping("otheruserhome")
	public ModelAndView otheruserhome(HttpServletRequest request, HttpSession session,ModelAndView modelAndView) {
		User user1=(User) session.getAttribute("user");
		if(user1!=null) {     //此用户已经登陆，可以查看除尽自己可见的所有文章
			String userName = request.getParameter("userName");
			User user = uServiceI.Login(userName);
			if (user == null) {
				modelAndView.setViewName("/community/jsp/other/nonetips");
			} else if(user.getUserId()==user1.getUserId()) {
				modelAndView.setViewName("redirect:/user/userhome.do");
				return modelAndView;
			}else {
				String permission="B_self";
				Integer otheruserId=user.getUserId();
				List<Essay> otheruseressaylist=essayServiceI.ShowUserEssayByDateLimit(otheruserId, permission);
				modelAndView.addObject("otheruseressaylist", otheruseressaylist);
				/*******************评论显示文章*********************/
				List<Integer> essayIdList=commentServiceI.FindEssayIdByUserId(otheruserId);
				List<Essay> essaylist=new ArrayList<Essay>();
				for (Integer essayId : essayIdList) {
					Essay essay=essayServiceI.FindEssayLimitLogin(essayId, permission);
					essaylist.add(essay);
				}
				modelAndView.addObject("essaylist", essaylist);
				modelAndView.addObject("otheruserName", userName);
				session.setAttribute("otheruser", user);
				modelAndView.setViewName("/community/jsp/user/otheruserhome");
			}
		}else {
			String userName = request.getParameter("userName");
			User user = uServiceI.Login(userName);
			if (user == null) {
				modelAndView.setViewName("/community/jsp/other/nonetips");
			} else {
				String permission="B_all";
				Integer otheruserId=user.getUserId();
				List<Essay> otheruseressaylist=essayServiceI.ShowUserEssayByDate(otheruserId, permission);
				modelAndView.addObject("otheruseressaylist", otheruseressaylist);
				/*******************评论显示文章*********************/
				List<Integer> essayIdList=commentServiceI.FindEssayIdByUserId(otheruserId);
				List<Essay> essaylist=new ArrayList<Essay>();
				for (Integer essayId : essayIdList) {
					Essay essay=essayServiceI.FindEssayLimitLogout(essayId, permission);
					essaylist.add(essay);
				}
				modelAndView.addObject("essaylist", essaylist);
				modelAndView.addObject("otheruserName", userName);
				session.setAttribute("otheruser", user);
				modelAndView.setViewName("/community/jsp/user/otheruserhome");
			}
		}

		return modelAndView;
	}

    /**
    　　* @param request modelAndView
    　　* @return modelAndView
    　　* @author：千夜
    　　* @date 2019/5/22 15:48
     　 * @description: TODO:查询其他用户所有可见的文章
    　　*/
    @RequestMapping("OtherUserEssay")
	public ModelAndView OtherUserEssay(HttpServletRequest request,ModelAndView modelAndView){
        User user= (User) request.getSession().getAttribute("user");
        String currentpage = request.getParameter("currentPage");
        if(user!=null){
            Integer userId=Integer.valueOf(request.getParameter("otherUserId")).intValue();
            /**************************分页获取相关参数************************************/
            String Page = request.getParameter("currentPage");
            Integer currentPage;
            if (null != Page) {
                currentPage = Integer.valueOf(Page).intValue();
            } else {
                currentPage = 1;
            }
            pojo.Page page = new Page();
            page.setLimitNumber(LimitNumber);
            page.setCurrentPage(currentPage);
            PageReturn pageReturn = new PageReturn();
            page = pageReturn.ReturnPage(page);//填充page实体
            Integer locationPage = currentPage;
            modelAndView.addObject("currentPage", locationPage);
            /*************************************************************************/
            List<EssayAndUser> list=uServiceI.FindOtherUserEssayLogin(userId,page);
            Integer listCount=uServiceI.FindOtherUserEssayCountLogin(userId);
            modelAndView.addObject("essaylist",list);
            modelAndView.addObject("essayListCount",listCount);
            modelAndView.addObject("otherUserId",userId);
            modelAndView.setViewName("/community/jsp/user/userAllEssay");
        }else{
            Integer userId=Integer.valueOf(request.getParameter("otherUserId")).intValue();
            /**************************分页获取相关参数************************************/
            String Page = request.getParameter("currentPage");
            Integer currentPage;
            if (null != Page) {
                currentPage = Integer.valueOf(Page).intValue();
            } else {
                currentPage = 1;
            }
            pojo.Page page = new Page();
            page.setLimitNumber(LimitNumber);
            page.setCurrentPage(currentPage);
            PageReturn pageReturn = new PageReturn();
            page = pageReturn.ReturnPage(page);//填充page实体
            Integer locationPage = currentPage;
            modelAndView.addObject("currentPage", locationPage);
            /*************************************************************************/
            List<EssayAndUser> list=uServiceI.FindOtherUserEssayLogout(userId,page);
            Integer listCount=uServiceI.FindOtherUserEssayCountLogout(userId);
            modelAndView.addObject("essaylist",list);
            modelAndView.addObject("essayListCount",listCount);
            modelAndView.addObject("otherUserId",userId);
            modelAndView.setViewName("/community/jsp/user/userAllEssay");
        }

		return modelAndView;
	}
}
